"use client"

import { useState, createContext, useContext, type ReactNode } from "react"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { messages, type Locale } from "@/lib/i18n"

type LocaleContextType = {
  locale: Locale
  setLocale: (locale: Locale) => void
  t: (key: string) => string // Translation function
}

const LocaleContext = createContext<LocaleContextType | undefined>(undefined)

export function LocaleProvider({ children }: { children: ReactNode }) {
  const [locale, setLocale] = useState<Locale>("zh") // Default to Chinese

  const t = (key: string) => {
    const path = key.split(".")
    let current: any = messages[locale]
    for (const p of path) {
      if (current && typeof current === "object" && p in current) {
        current = current[p]
      } else {
        console.warn(`Translation key "${key}" not found for locale "${locale}"`)
        return key // Fallback to key if not found
      }
    }
    return typeof current === "string" ? current : key
  }

  return <LocaleContext.Provider value={{ locale, setLocale, t }}>{children}</LocaleContext.Provider>
}

export function useLocale() {
  const context = useContext(LocaleContext)
  if (context === undefined) {
    throw new Error("useLocale must be used within a LocaleProvider")
  }
  return context
}

export function LanguageSwitcher() {
  const { locale, setLocale } = useLocale()
  return (
    <Select onValueChange={(value: Locale) => setLocale(value)} defaultValue={locale}>
      <SelectTrigger className="w-[120px]">
        <SelectValue placeholder="Language" />
      </SelectTrigger>
      <SelectContent>
        <SelectItem value="zh">中文</SelectItem>
        <SelectItem value="en">English</SelectItem>
      </SelectContent>
    </Select>
  )
}
